#include <sys/types.h>
#include <regex.h>

#include "search.h"
#include "buffer.h"

#define TRUE 1
#define FALSE 0

static regex_t preg;
static buf_t *start_buf;
static int start_offset;

static buf_t *buf = NULL;
static int offset = 0;

int find_start(const char *regex, buf_t *buf, int offset)
{
    start_buf = buf;
    start_offset = offset;
    return regcomp(&preg, regex, 0);
}

void find_finish(void)
{
    start_buf = NULL;
    start_offset = 0;
    buf = NULL;
    offset = 0;
    regfree(&preg);
}

find_result_t * find_next()
{
    static regmatch_t match;
    static find_result_t result;
    static int found = FALSE;

    if (buf == NULL) {
	buf = start_buf;
	offset = start_offset;
    }

    while (regexec(&preg, buf->data + offset, 1, &match, 0) == REG_NOMATCH) {
	buf = buf_next_circular(buf);
	if (buf == start_buf && offset == 0 && found == FALSE) {
	    return NULL;
	} else {
	    offset = 0;
	}
    }

    found = TRUE;
    match.rm_so += offset;
    match.rm_eo += offset;
    offset = match.rm_eo;

    result.buf = buf;
    result.match = &match;
    return &result;
}
